package com.edu.jsu.file.controller;


import com.edu.jsu.commonutils.R;
import com.edu.jsu.file.entity.Document;
import com.edu.jsu.file.service.DocumentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 * 文件 前端控制器
 * </p>
 *
 * @author 廖俊杰
 * @since 2021-12-01
 */
@RestController
@RequestMapping("/file/document")
public class DocumentController {

    private static final Logger LOG = LoggerFactory.getLogger(DocumentController.class);

    private static final String FILE_PATH = "F:/file/";

    @Resource
    private DocumentService documentService;

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        LOG.info("上传文件开始：{}",file);
        LOG.info("上传文件文件名：{}",file.getOriginalFilename());
        LOG.info("上传文件大小：{}",String.valueOf(file.getSize()));

        //保存文件到本地
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);

        String key = UUID.randomUUID().toString().replace("-", "");
        String fulPath = FILE_PATH+"lecture/"+key+"."+suffix;
        File dest = new File(fulPath);
        file.transferTo(dest);
        LOG.info(dest.getAbsolutePath());
        LOG.info("保存文件记录开始");
        Document  fileDto = new Document();
        fileDto.setName(fileName);
        fileDto.setUrl(fulPath);
        fileDto.setSize(Math.toIntExact(file.getSize()));
        fileDto.setSuffix(suffix);
        documentService.save(fileDto);
        return R.ok().data("result","保存成功").data("fileName",fileName).data("path",fulPath);
    }
}

